import axios from 'axios'
import qs from 'qs'
import httpUrl from './http_url'

/* eslint-disable*/
axios.interceptors.request.use(config => {    // 这里的config包含每次请求的内容
  // 判断localStorage中是否存在api_token
  if (localStorage.getItem('api_token')) {
    //  存在将api_token写入 request header
    config.headers.apiToken = `${localStorage.getItem('api_token')}`;
  }
  return config;
}, err => {
  return Promise.reject(err);
});

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
});

function statusCode (response) {
  let message = '';
  switch (response.status) {
    case 400:
      return message = '请求错误'
      break
    case 401:
      return message = '未授权，请登录'
      break
    case 403:
      return message = '拒绝访问'
      break
    case 404:
      return message = `请求地址出错: ${response.config.url}`
      break
    case 408:
      return message = '请求超时'
      break
    case 500:
      return message = '服务器内部错误'
      break
    case 501:
      return message = '服务未实现'
      break
    case 502:
      return message = '网关错误'
      break
    case 503:
      return message = '服务不可用'
      break
    case 504:
      return message = '网关超时'
      break
    case 505:
      return message = 'HTTP版本不受支持'
      break
    default:
  }
}

function checkStatus (response) {
  // 如果http状态码正常，则直接返回数据
  if (response && (response.status === 200 || response.status === 304 ||
      response.status === 400)) {
    return response
  }
  // 异常状态下，把错误信息返回去
  return {
    status: response.status,
    msg: statusCode (response)
  }
}

function checkCode (res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  console.log(statusCode (res),res.status)
  if (res.data && (!res.data.success)) {
    // alert(res.data.error_msg)
  }
  return res
}
// 请求方式的配置
export default {
  post (url, data) {  //  post
    return axios({
      method: 'post',
      baseURL: httpUrl.localBaseUrl,
      url,
      data: qs.stringify(data),
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get (url, params) {  // get
    return axios({
      method: 'get',
      baseURL: httpUrl.localBaseUrl,
      url,
      params, // get 请求时带的参数
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
